<template>
  <div class="home">
    <!-- 搜索区域 -->
    <section class="search-section">
      <div class="container">
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索品牌、车型..."
            size="large"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </div>
        
        <div class="quick-filters">
          <el-radio-group v-model="quickFilter" @change="handleQuickFilter">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="suv">SUV</el-radio-button>
            <el-radio-button label="sedan">轿车</el-radio-button>
            <el-radio-button label="new">准新车</el-radio-button>
            <el-radio-button label="cheap">5万以下</el-radio-button>
          </el-radio-group>
        </div>
      </div>
    </section>

    <!-- 推荐车辆 -->
    <section class="recommend-section">
      <div class="container">
        <h2 class="section-title">热门推荐</h2>
        
        <!-- 加载状态 -->
        <div v-if="carStore.loading" class="loading-container">
          <el-skeleton :rows="6" animated />
        </div>
        
        <!-- 数据展示 -->
        <div v-else class="car-grid">
          <el-card 
            v-for="car in recommendCars" 
            :key="car.id"
            class="car-card"
            shadow="hover"
            @click="$router.push(`/car/${car.id}`)"
          >
            <div class="car-image">
              <img 
                :src="getCarImage(car)" 
                :alt="car.title"
                @error="handleImageError"
              >
              <div class="car-tags">
                <el-tag v-if="car.is_new" type="success" size="small">准新车</el-tag>
                <el-tag v-if="car.hot" type="danger" size="small">热门</el-tag>
              </div>
            </div>
            <div class="car-info">
              <h3 class="car-title">{{ car.title }}</h3>
              <p class="car-desc">{{ car.subtitle || car.description }}</p>
              <div class="car-meta">
                <span>{{ car.distance }}万公里</span>
                <span>{{ formatRegDate(car.reg_date) }}上牌</span>
                <span>{{ car.location }}</span>
              </div>
              <div class="car-price">
                <span class="price">{{ car.price }}万</span>
                <span class="original-price" v-if="car.original_price">
                  新车{{ car.original_price }}万
                </span>
              </div>
            </div>
          </el-card>
        </div>
        
        <!-- 空状态 -->
        <div v-if="!carStore.loading && recommendCars.length === 0" class="empty-state">
          <el-empty description="暂无推荐车辆" />
        </div>
      </div>
    </section>

    <!-- 品牌专区 -->
    <section class="brand-section">
      <div class="container">
        <h2 class="section-title">品牌专区</h2>
        <div class="brand-grid">
          <div 
            v-for="brand in brands" 
            :key="brand.id"
            class="brand-item"
            @click="handleBrandClick(brand.value)"
          >
            <img :src="brand.logo" :alt="brand.name">
            <span>{{ brand.name }}</span>
          </div>
        </div>
      </div>
    </section>

    <!-- 服务保障 -->
    <section class="service-section">
      <div class="container">
        <h2 class="section-title">瓜子服务保障</h2>
        <div class="service-grid">
          <div class="service-item">
            <el-icon size="48" color="#ff6a00"><Check /></el-icon>
            <h3>259项专业检测</h3>
            <p>专业评估师全面检测</p>
          </div>
          <div class="service-item">
            <el-icon size="48" color="#ff6a00"><Lock /></el-icon>
            <h3>1年2万公里质保</h3>
            <p>享受官方质保服务</p>
          </div>
          <div class="service-item">
            <el-icon size="48" color="#ff6a00"><Star /></el-icon>
            <h3>7天无理由退车</h3>
            <p>购车无忧保障</p>
          </div>
          <div class="service-item">
            <el-icon size="48" color="#ff6a00"><Phone /></el-icon>
            <h3>24小时客服</h3>
            <p>全程专业服务</p>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Search, 
  Check, 
  Lock, 
  Star, 
  Phone
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useCarStore } from '@/store/car'

const router = useRouter()
const carStore = useCarStore()

const searchKeyword = ref('')
const quickFilter = ref('all')

// 品牌数据 - 与CarList.vue保持一致
const brands = [
  { id: 1, name: '大众', value: 'volkswagen', logo: '/images/brands/vw.png' },
  { id: 2, name: '丰田', value: 'toyota', logo: '/images/brands/toyota.png' },
  { id: 3, name: '本田', value: 'honda', logo: '/images/brands/honda.png' },
  { id: 4, name: '奔驰', value: 'benz', logo: '/images/brands/benz.png' },
  { id: 5, name: '宝马', value: 'bmw', logo: '/images/brands/bmw.png' },
  { id: 6, name: '奥迪', value: 'audi', logo: '/images/brands/audi.png' }
]

// 使用计算属性获取推荐车辆 - 取前6辆作为推荐
const recommendCars = computed(() => {
  return carStore.carList.slice(0, 6)
})

// 获取车辆图片
const getCarImage = (car) => {
  if (car.images && car.images.length > 0) {
    return car.images[0]
  }
  if (car.main_image) {
    // 使用store中的图片处理函数
    return carStore.getFullImageUrl(car.main_image)
  }
  return '/images/default-car.png'
}

// 图片加载错误处理
const handleImageError = (e) => {
  e.target.src = '/images/default-car.png'
}

// 格式化上牌日期
const formatRegDate = (regDate) => {
  if (!regDate) return '未知'
  if (regDate instanceof Date) {
    return regDate.toISOString().split('T')[0].replace(/-/g, '-')
  }
  if (typeof regDate === 'string') {
    return regDate.split('T')[0]
  }
  return regDate
}

const handleSearch = () => {
  router.push({
    path: '/cars',
    query: { keyword: searchKeyword.value }
  })
}

const handleQuickFilter = (filter) => {
  router.push({
    path: '/cars',
    query: { filter }
  })
}

const handleBrandClick = (brandValue) => {
  router.push({
    path: '/cars',
    query: { brand: brandValue }
  })
}

onMounted(async () => {
  try {
    // 获取车辆列表数据
    await carStore.fetchCarList({ limit: 12 })
  } catch (error) {
    console.error('获取推荐车辆失败:', error)
    ElMessage.error('获取推荐车辆失败')
  }
})
</script>

<style lang="scss" scoped>
.home {
  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }
}

.search-section {
  background: linear-gradient(135deg, #ff6a00, #ff8c00);
  padding: 60px 0 40px;
  color: white;

  .search-box {
    max-width: 600px;
    margin: 0 auto 30px;
  }

  .quick-filters {
    display: flex;
    justify-content: center;
  }
}

.recommend-section {
  padding: 60px 0;

  .section-title {
    text-align: center;
    margin-bottom: 40px;
    font-size: 28px;
    color: #333;
  }

  .car-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 24px;
  }

  .car-card {
    cursor: pointer;
    transition: transform 0.3s;

    &:hover {
      transform: translateY(-5px);
    }

    .car-image {
      position: relative;
      height: 200px;
      overflow: hidden;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s;
      }

      .car-tags {
        position: absolute;
        top: 10px;
        left: 10px;
        display: flex;
        gap: 5px;
      }
    }

    .car-info {
      padding: 15px;

      .car-title {
        margin: 0 0 8px;
        font-size: 16px;
        color: #333;
      }

      .car-desc {
        margin: 0 0 12px;
        color: #666;
        font-size: 14px;
      }

      .car-meta {
        display: flex;
        justify-content: space-between;
        margin-bottom: 12px;
        font-size: 12px;
        color: #999;
      }

      .car-price {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .price {
          font-size: 20px;
          font-weight: bold;
          color: #ff6a00;
        }

        .original-price {
          font-size: 12px;
          color: #999;
          text-decoration: line-through;
        }
      }
    }
  }
}

.brand-section {
  padding: 60px 0;
  background: #f8f9fa;

  .section-title {
    text-align: center;
    margin-bottom: 40px;
    font-size: 28px;
    color: #333;
  }

  .brand-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 20px;
  }

  .brand-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    background: white;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    img {
      width: 60px;
      height: 60px;
      margin-bottom: 10px;
      object-fit: contain;
    }

    span {
      font-size: 14px;
      color: #333;
    }
  }
}

.service-section {
  padding: 60px 0;

  .section-title {
    text-align: center;
    margin-bottom: 40px;
    font-size: 28px;
    color: #333;
  }

  .service-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 30px;
  }

  .service-item {
    text-align: center;
    padding: 30px 20px;

    h3 {
      margin: 15px 0 10px;
      font-size: 18px;
      color: #333;
    }

    p {
      color: #666;
      margin: 0;
    }
  }
}

.loading-container {
  padding: 40px 0;
}

.empty-state {
  padding: 60px 0;
}

@media (max-width: 768px) {
  .search-section {
    padding: 40px 0 30px;
  }

  .recommend-section,
  .brand-section,
  .service-section {
    padding: 40px 0;
  }

  .car-grid {
    grid-template-columns: 1fr !important;
  }

  .brand-grid {
    grid-template-columns: repeat(3, 1fr) !important;
  }

  .service-grid {
    grid-template-columns: repeat(2, 1fr) !important;
  }
}
</style>